$(function () {
    initSysModeTable();
})

var dialogWating;
function initSysModeTable(){
    dialogWating = showWating({msg:'正在拼命的加载中...'});
    $.ajax({
        url:oauthModules+"/oauthSysMode/listAll",
        type:"GET",
        dataType:"json",
        success:function(data) {
            data = data.data;
            closeWating(null,dialogWating);
            var $table = $("#table");
            $('#table').bootstrapTable('destroy').bootstrapTable({
                columns:[
                    {
                        title:'隶属平台',
                        field:'sysname',
                        align:'left',
                        width:250,
                        formatter:function(value, row, index) {
                            return value;
                        }
                    },
                    {
                        title:'状态',
                        field:'sys_mode_status',
                        width:120,
                        align:'left',
                        formatter:function(value, row, index) {
                            if(value == 0){
                                return "<span class='m-badge m-badge--info'>正常</span>"
                            }
                            if(value == 1){
                                return "<span class='m-badge m-badge--success'>冻结</span>"
                            }
                            if(value == 2){
                                return "<span class='m-badge m-badge--danger'>禁用</span>"
                            }
                            return "<span class='m-badge m-badge--info'>缺省</span>"
                        }
                    },
                    {
                        title:'创建人',
                        field:'createBy',
                        align:'left',
                        width:120
                    },
                    {
                        title:'创建日期',
                        field:'create_time',
                        align:'left',
                        width:150,
                        formatter:function(value, row, index) {
                            return dateformat(value);
                        }
                    },
                    {
                        title:'修改人',
                        field:'modifiedBy',
                        align:'left',
                        width:160
                    },
                    {
                        title:'修改日期',
                        field:'update_time',
                        align:'left',
                        width:160,
                        formatter:function(value, row, index) {
                            return dateformat(value);
                        }
                    },
                    {
                        title:'操作',
                        field:'sys_mode_id',
                        formatter:function(value, row, index) {
                            var sysname = row.sysname;
                            var sys_mode_status = row.sys_mode_status;
                            return '<button onclick=detail("'+sysname+'","'+sys_mode_status+'") class="m-portlet__nav-link btn m-btn m-btn--hover-accent m-btn--icon m-btn--icon-only m-btn--pill" title="详情">' +
                            '<i class="la la-eye"></i>' +
                            '</button>'
                        }
                    }],
                data:data,
                method:'post',//请求方式(*)
                cache:false,//是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性(*)
                pagination:false,//是否显示分页(*)
                sortable:true,//是否启用排序
                sortOrder:"desc",//排序方式
                sidePagination:"server",//分页方式：client客户端分页，server服务端分页(*)
                showColumns:false,//是否显示所有的列
                showRefresh:false,//是否显示刷新按钮
                minimumCountColumns:2,//最少允许的列数
                clickToSelect:true,//是否启用点击选中行
                detailView:true,//是否显示父子表    *关键位置*
                contentType:"application/json;charset=UTF-8",
                checkboxHeader:true,
                search:false,
                singleSelect:true,
                striped:false,
                showColumns:false,//开启自定义列显示功能
                height: $(window).height() - 200 ,
                //注册加载子表的事件。你可以理解为点击父表中+号时触发的事件
                // expanderExpandedClass:'fa fa-caret-down',
                // expanderCollapsedClass:'fa fa-caret-right',
                onExpandRow:function(index, row, $detail) {
                    var cur_table = $detail.html('<table></table>').find('table');
                    var html = "";
                    html += "<div style='text-align: left;padding-top:1px;padding-bottom:1px;background:#ebedf2;border-radius:0px;'><table  class='table' style='width: 100%;' id='table"+index+"'>";
                    html += "</table></div>";
                    $detail.html(html);
                    initTreeTable("table"+index,row);
                }
            });
        }
    });
}

function detail(sysname,sys_mode_status){
    var sysname = "隶属平台:"+sysname;
    if(sys_mode_status == 0){
        sys_mode_status = "正常";
    }else if(sys_mode_status == 1){
        sys_mode_status = "冻结";
    }else if(sys_mode_status == 2){
        sys_mode_status = "禁用";
    }else{
        sys_mode_status = "缺省";
    }
    sys_mode_status = "状态:"+sys_mode_status;
    window.parent.toastrBoot(1,sysname+"<br>"+sys_mode_status);
}

function initTreeTable(tableId,row){
    dialogWating = showWating({msg:'正在拼命的加载中...'});
    $.ajax({
        url:oauthModules+'/oauthResources/all/list?sys_mode_id='+row.sys_mode_id,
        type:"GET",
        dataType:"json",
        success:function(data) {
            var $table = $("#"+tableId);
            data = eval("(" + data.data + ")");
            $table.bootstrapTable('destroy').bootstrapTable({
                data:data,
                striped:false,
                class:'table table-hover table-bordered',
                sidePagination:"client",//表示服务端请求
                pagination:false,
                treeView:true,
                treeId:"id",
                // height:tableHeight()*0.7,
                treeField:"name",
                sortable:false,//是否启用排序
                columns:[
                    /* 
                    {
                        field: 'ck',
                        checkbox:true
                    }, 
                    */
                    {
                        field:'name',
                        width:270,
                        title:'名称',
                        formatter:'nameFormatter'
                    },
                    {
                        field:'tempObject',
                        width:120,
                        title:'类型',
                        formatter:'tempObjectFormatter'
                    },
                    {
                        field:'integerappend',
                        width:120,
                        title:'数据权限',
                        formatter:'authorFormatter'
                    },
                    {
                        field:'integerappend',
                        width:150,
                        title:'拦截类型',
                        formatter:'authorTypeFormatter'
                    },
                    {
                        field:'buessid',
                        title:'操作',
                        formatter:'btnFormatter'
                    }
                ],
                onLoadSuccess:function(data){

                }
            });
            closeWating(null,dialogWating);
        }
    });
}

//数据权限
function authorFormatter(value, row, index){
    var integerappend = row.integerappend;
    if(integerappend != null && integerappend != ""){
        var val = integerappend.split(",");
        if(val[0] == 0){
            return "<font color='red'>是</font>";
        }else if(val[0] == 1){
            return "否";
        }
    }
}


function nameFormatter(value, row, index){
    var data = row.tempObject;
    if("Sources" == data){
        return value;
    }
    if("Function" == data){
        return value;
    }
}

function tempObjectFormatter(value, row, index){
    var data = row.tempObject;
    if("Sources" == data){
        return "<span class='label label-lg font-weight-bold label-light-primary label-inline'>资源</span>";
    }
    if("Function" == data){
        return "<span class='label label-lg font-weight-bold label-light-info label-inline'>功能</span>";
    }
    return "缺省";
}

//拦截类型
function authorTypeFormatter(value, row, index){
    var val = value.split(",");
    if(val[1] == 0){
        return "无需拦截"
    }else if(val[1] == 1){
        return "<font color='red'>必须拦截</font>";
    }
}

//格式化按钮
function btnFormatter(value, row, index){
    var tempObject = row.tempObject;
    var name = row.name;
    console.log(value,name)
    if(tempObject == 'Sources'){
        return '<span class="dropdown">' +
                    '<a href="#" class="btn m-btn m-btn--hover-brand m-btn--icon m-btn--icon-only m-btn--pill" data-toggle="dropdown" aria-expanded="true">' +
                        '<i class="la la-ellipsis-h"></i>' +
                    '</a>' +
                    '<div class="dropdown-menu dropdown-menu-right">' +
                        '<button class="dropdown-item" onclick=addXtMenuinfo("'+value+'","'+name+'")><i class="la la-edit"></i>添加子资源</button>' +
                        '<button class="dropdown-item" onclick=chXtMenuinfo("'+value+'","'+name+'")><i class="fa fa-edit"></i>设为一级资源</a>' +
                    '</div>' +
                '</span>' +
                '<button onclick=updateXtMenuinfo("'+value+'") class="m-portlet__nav-link btn m-btn m-btn--hover-accent m-btn--icon m-btn--icon-only m-btn--pill" title="编辑">' +
                    '<i class="fa fa-magic fa-lg"></i>' +
                '</button>'+
                '<button onclick=delXtMenuinfo("'+value+'") class="m-portlet__nav-link btn m-btn m-btn--hover-danger m-btn--icon m-btn--icon-only m-btn--pill" title="删除">' +
                    '<i class="fa fa-trash-o"></i>' +
                '</button>'

        // return '<a href=javascript:addXtMenuinfo("'+value+'","'+name+'") class="btn btn-default" title="添加子资源"><i class="glyphicon glyphicon-plus">添加子资源</i></a><a href=javascript:chXtMenuinfo("'+value+'","'+name+'") class="btn btn-default" title="设为一级资源"><i class="glyphicon glyphicon-pencil">设为一级资源</i></a><a href=javascript:updateXtMenuinfo("'+value+'") title="编辑" class="btn btn-default"><i class="fa fa-edit">编辑</i></a><a href=javascript:delXtMenuinfo("'+value+'") class="btn btn-default" title="删除"><i class="fa fa-trash-o">删除</i></a>';
    }
}

function chXtMenuinfo(value,valueText){
    msgTishCallFnBoot("确定将资源<font color=red>【"+valueText+"】</font>设为一级资源？",function(){
        var params = {resources_id:value};
        ajaxBRequestCallFn(oauthModules+'/oauthResources/chMenuInfo',params,function(result){
            try {
                if(typeof(result.success) != "undefined"){
                    if(result.success){
                        window.parent.toastrBoot(3,result.message);
                        initSysModeTable();
                    }else{
                        window.parent.toastrBoot(4,result.message);
                    }
                }
            } catch (e) {

            }
        });
    })
}
function delXtMenuinfo(value){
    if(value == null){
        toastrBoot(4,"未能获取该数据编号");
        return;
    }
    msgTishCallFnBoot("确定删除该数据？",function(){
        var params = {resources_id:value, _method:'DELETE'};
        ajaxBRequestCallFn(oauthModules+'/oauthResources/delete',params,function(result){
            try {
                if(typeof(result.success) != "undefined"){
                    if(result.success){
                        window.parent.toastrBoot(3,result.message);
                        initSysModeTable();
                    }else{
                        window.parent.toastrBoot(4,result.message);
                    }
                }
            } catch (e) {

            }
        },null,"DELETE");
    })
}
function expandTree(){
    dialogWating = showWating({msg:'正在操作中...'});
    $('#table').bootstrapTable("expandAllTree")
    closeWating(null,dialogWating);
}
function collapseTree(){
    dialogWating = showWating({msg:'正在操作中...'});
    $('#table').bootstrapTable("collapseAllTree")
    closeWating(null,dialogWating);
}

function changeMenuinfoSelect(){
    var SourcesModalCount = 0 ;
    $('#changeXtMenuinfoBody').height(300);
    $('#changeXtMenuinfoModal').modal({backdrop:'static',keyboard:false});
    $('#changeXtMenuinfoModal').modal({"backdrop":"static"}).modal('show').on("shown.bs.modal",function(){
        if(++SourcesModalCount == 1) {
            treeObj = $.fn.zTree.init($("#tree"), null,[]);
            $(".ztree").append("暂无数据");
            initComboData("sysmode_id",oauthModules+"/oauthSysMode/listAll","sys_mode_id","sysname");
        }
    });
}
//单击事件
function onClick(event, treeId, treeNode, msg){
}

/**
 * 下拉框变化筛选菜单树
 * @param thiz
 */
function doThisEvent(thiz) {
    var setting = {
        view:{
            selectedMulti:false
        },
        check:{
            enable:false
        },
        data:{
            //必须使用data
            simpleData:{
                enable:true,
                idKey:"id",//id编号命名 默认
                pIdKey:"pId",//父id编号命名 默认
                rootPId:0 //用于修正根节点父节点数据，即 pIdKey 指定的属性值
            }
        },
        edit:{
            enable:false
        },
        callback:{
            onClick:onClick//单击事件
        }
    };
    var zTreeNodes;
    dialogWating = showWating({msg:'正在拼命的加载中...'});
    var parm = {"sysmode_id":thiz.value};
    ajaxBRequestCallFn(oauthModules+'/oauthResources/bZTree',parm,function(result){
        zTreeNodes = eval("(" + result.data + ")");
        if(undefined == result.data || null == result.data || result.data == "" || result.data == "[]"){
            treeObj = $.fn.zTree.init($("#tree"), setting,[]);
            $(".ztree").append("暂无数据");
        }else{
            treeObj = $.fn.zTree.init($("#tree"), setting,zTreeNodes);
        }
        closeWating(null,dialogWating);
    },null,"GET");
}

function doXtMenuinfoSel(){
    var id = $('#resources_id').val();
    var zTree = $.fn.zTree.getZTreeObj("tree"),
        nodes = zTree.getSelectedNodes();
    if (nodes.length != 1) {
        toastrBoot(4,"请选择资源");
        return;
    }

    var node = zTree.getNodes();
    var treeNode;
    var nodesarray = zTree.transformToArray(node);
    for(var i = 0; i < nodesarray.length; i++){
        if(nodesarray[i].id == id){
            treeNode = nodesarray[i];
            break;
        }
    }

    if(undefined == treeNode){
        treeNode =  nodes[0];
    }else{
        var result = '';
        result = getChildNodes(treeNode,result);
        result = treeNode.id + ","+result;
        if(result.indexOf(nodes[0].id) >= 0){
            toastrBoot(4,"您选择的上级资源不合法");
            return;
        }
    }

    msgTishCallFnBoot("确定要选择【<font color=red>"+nodes[0].name+"</font>】？",function(){
        $('#resources_parentidTitle_').val(nodes[0].name);
        $('#resources_parentid_').val(nodes[0].id);
        $('#changeXtMenuinfoModal').modal('hide');
    })
}

function InitMenuModuleListSetV(id,value_id){
    $("#"+id).html("");;
    var str = "<option value=''>请选择</option>";

    var params = {};
    ajaxBRequestCallFn(oauthModules+'/oauthSysModules/listAll',params,function(result){
        result = result.data;
        //从服务器获取数据进行绑定
        $.each(result, function(i, item){
            str += "<option value=" + item.sys_modules_id + ">" + item.sysname+ " -----  "+ item.sys_modules_name + "</option>";
        })
        $("#"+id).append(str);
        try {
            if(null != value_id && '' != value_id){
                if('undefined' != typeof($('#'+value_id).val()) && null != $('#'+value_id).val() && '' != $('#'+value_id).val() && '请选择' != $('#'+value_id).val()){
                    $('#'+id).val($('#'+value_id).val());
                }
            }
        } catch (e) {
            console.log("读取下拉框并赋值出现异常，异常信息："+e);
        }
    },null,"POST");
}


